<template>
  <div class="page-modal">
    <el-dialog
      v-model="dialogVisible"
      title="Tips"
      width="500px"
      :before-close="handleClose"
    >
      <xjhForm v-bind="modalConfig" v-model="formData"></xjhForm>
      <div class="default-slot">
        <slot></slot>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmClick">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, defineProps, defineExpose, watch } from 'vue';
import xjhForm from '@/base-ui';
import type { IForm } from '@/base-ui';
import { useStore } from '@/store';

const props = defineProps({
  modalConfig: {
    type: Object as () => IForm,
    required: true
  },
  defaultFromData: {
    type: Object,
    default: () => ({})
  },
  otherFromData: {
    type: Object,
    default: () => ({})
  },
  pageName: {
    type: String,
    required: true
  }
});

let dialogVisible = ref(false);
const formData = ref<any>({});
const store = useStore();

watch(
  () => props.defaultFromData,
  function (val) {
    for (const item of props.modalConfig.formItems) {
      formData.value[`${item.filed}`] = val[`${item.filed}`];
    }
  }
);

const handleClose = () => {
  dialogVisible.value = false;
};

const handleConfirmClick = () => {
  dialogVisible.value = false;
  if (Object.keys(props.defaultFromData).length) {
    // 编辑
    store.dispatch('system/editPageDataAction', {
      pageName: props.pageName,
      editData: { ...formData.value, ...props.otherFromData },
      id: props.defaultFromData.id
    });
  } else {
    // 新建
    store.dispatch('system/createPageDataAction', {
      pageName: props.pageName,
      newData: { ...formData.value, ...props.otherFromData }
    });
  }
};

defineExpose({
  dialogVisible
});
</script>

<style lang="less" scoped>
.page-modal {
  color: red;
}
.default-slot {
  margin-left: 20px;
}
</style>
